package com.cz.basetool.ui_work.util.system.gps;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationProvider;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.util.Pair;

import com.cz.basetool.ui_work.util.log.AndroidConsoleLogPrinter;

/**
 * Created by XinYi on 2019/4/29.
 * 用于简单的定位，获取经纬度。
 */
public class GpsLocationWorker {
    private static final String TAG = "GpsLocationWorker";
    private LocationTracker tracker;

    private double latitude = 0.0;        //纬度
    private double longitude = 0.0;      //经度

    private static final GpsLocationWorker ourInstance = new GpsLocationWorker();
    private AlertDialog gpsPermissionSetTipDialog;

    public static GpsLocationWorker getInstance() {
        return ourInstance;
    }

    private GpsLocationWorker() {
    }

    private void dialogTipOpenGps(final Context context) {
        //对于没有系统签名，可能需要人工干预开启gps。
        gpsPermissionSetTipDialog = new AlertDialog.Builder(context)
                .setTitle("温馨提示")
                .setMessage("去打开GPS开关")
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                gpsPermissionSetTipDialog.dismiss();
                            }
                        })
                .setPositiveButton("设置",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                context.startActivity(intent);
                            }
                        })

                .setCancelable(false)
                .show();
    }

    /**
     * 开启定位
     *
     * @param context 必须是Activity
     */
    public void startLocate(Context context) {
        if (tracker != null) return;

        boolean oPen = GpsUtil.isOPen(context);
        AndroidConsoleLogPrinter.d("cz", "startLocate: " + oPen);
        if (oPen == false) {
            dialogTipOpenGps(context);
        }

        TrackerSettings settings =
                new TrackerSettings()
                        .setUseGPS(true)
                        .setUseNetwork(true)                //如果想准确定位，不能用网络定位。
                        .setUsePassive(false)
                        .setTimeout(24 * 60 * 60 * 1000)
                        .setTimeBetweenUpdates(1000)
                        .setMetersBetweenUpdates(1);

        tracker = new LocationTracker(context, settings) {

            @Override
            public void onNmeaReceived(long timestamp, String nmea) {

            }

            @Override
            public void onGpsStatusChanged(int event) {
                int count = 0;
                switch (event) {
                    // 第一次定位
                    case GpsStatus.GPS_EVENT_FIRST_FIX:
                        AndroidConsoleLogPrinter.i(TAG, "第一次定位");
                        break;
                    // 卫星状态改变
                    case GpsStatus.GPS_EVENT_SATELLITE_STATUS:

                        break;
                    // 定位启动
                    case GpsStatus.GPS_EVENT_STARTED:
                        AndroidConsoleLogPrinter.i(TAG, "定位启动");
                        break;
                    // 定位结束
                    case GpsStatus.GPS_EVENT_STOPPED:
                        LocationUtils.isLocationing = false;
                        StateFlag.setLocationState(0);
                        AndroidConsoleLogPrinter.i(TAG, "定位结束");
                        break;
                }
            }

            @Override
            public void onLocationFound(@NonNull Location location) {
                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
                LocationUtils.isLocationing = true;
            }

            /**
             * Called when the tracker had not found any location and the timeout just happened
             */
            @Override
            public void onTimeout() {
                LocationUtils.isLocationing = false;
                StateFlag.setLocationState(0);
            }

            @Override
            public void onStatusChanged(@NonNull String provider, int status, Bundle extras) {
                if (status == LocationProvider.OUT_OF_SERVICE || status ==
                        LocationProvider.TEMPORARILY_UNAVAILABLE) {
                    StateFlag.setLocationState(0);
                    LocationUtils.isLocationing = false;
                }
            }

            @Override
            public void onProviderError(@NonNull ProviderError providerError) {

                LocationUtils.isLocationing = false;
            }
        };
        tracker.startListening();
    }

    public void stopLocation() {
        if (tracker != null) {
            tracker.stopListening();
            tracker = null;
        }
    }

    /**
     * 获取当前经纬度
     *
     * @return
     */
    public Pair<Double, Double> getCurrentLocation() {
        return new Pair<>(longitude, latitude);
    }

    /**
     * 获取当前经纬度
     *
     * @return
     */
    public String getCurrentLocationStr() {
        return longitude + "," + latitude;
//        return "0.05,0.03";
    }
}
